﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Mads.CoreDomain;

namespace Mads.Administrator
{
  public partial class AdministratorGUI : Form
  {
    private int sessionId;
    private TrainManagerClient trainManagerClient = new TrainManagerClient();
    private User[] users;

    public Station[] massiveOfStations;
    public Dictionary<TimeSpan, Station> departure = new Dictionary<TimeSpan, Station>();
    public Dictionary<Station, TimeSpan> waitMinutes = new Dictionary<Station, TimeSpan>();

    public AdministratorGUI()
    {
      InitializeComponent();
      sessionId = trainManagerClient.InitUser();
      LoginGUI loginGUI = new LoginGUI(sessionId, trainManagerClient);
      if (loginGUI.ShowDialog() == DialogResult.OK)
      {

      }
      else
      {
        //this.Dispose();
        this.Close();
      }
      speedTypeComboBox.SelectedIndex = 0;
      RegularityComboBox.SelectedIndex = 0;

      massiveOfStations = trainManagerClient.GetStations(sessionId);
      StationCheckedListBox.Items.Clear();
      foreach (Station station in massiveOfStations)
      {
        StationCheckedListBox.Items.Add(station.Name);
      }
    }

    # region Работа с пользователями

    private void AddUserToolStripMenuItem_Click(object sender, EventArgs e)
    {
      AddUserGUI addUserGUI = new AddUserGUI(sessionId, trainManagerClient);
      if (addUserGUI.ShowDialog() == DialogResult.OK)
      {

      }
    }

    private void EditUserToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    private void DeleteUserToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }



    private void UserListView_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (UserListView.SelectedItems.Count == 1)
      {
        SetEnabledOfContextMenu(true);
      }
      else
      {
        SetEnabledOfContextMenu(false);
      }
    }

    private void SetEnabledOfContextMenu(bool isEnabled)
    {
      EditUserToolStripMenuItem.Enabled = isEnabled;
      DeleteUserToolStripMenuItem.Enabled = isEnabled;
    }

    private void InitializeList()
    {
      users = trainManagerClient.GetUsers();
      foreach (User user in users)
      {
        ListViewItem itemView = new ListViewItem(user.Login);
        itemView.SubItems.Add(user.PasswordHash);
        itemView.SubItems.Add("dsfsdfsdf");
        /*switch (user.Role)
        {
          case UserRole.Administrator:
            {
              itemView.SubItems.Add("Администратор");
              break;
            }
          case UserRole.Cashier:
            {
              itemView.SubItems.Add("Кассир");
              break;
            }
          case UserRole.User:
            {
              itemView.SubItems.Add("Пользователь");
              break;
            }
        }*/
        UserListView.Items.Add(itemView);
      }
    }

    # endregion

    private void MainTabControl_TabIndexChanged(object sender, EventArgs e)
    {
      if (MainTabControl.SelectedIndex == 0)
      {
        InitializeList();
      }
    }

    private void MainTabControl_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (MainTabControl.SelectedIndex == 0)
      {
        //InitializeList();
      }
    }

    private void AdministratorGUI_Load(object sender, EventArgs e)
    {

    }


    #region работа с маршрутами

    private void NextButton_Click(object sender, EventArgs e)
    {
      if (StationCheckedListBox.SelectedItems.Count == 0)
      {
        MessageBox.Show("Выберите станции, через которые будет проходить маршрут", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
      else
      {
        Station[] selectedStations= new Station[StationCheckedListBox.CheckedIndices.Count];
        int counter = 0;
        foreach(int index in StationCheckedListBox.CheckedIndices)
        {
          selectedStations[counter] = massiveOfStations[index];
          counter++;
        }

        AddStationToRouteGUI addStation = new AddStationToRouteGUI(selectedStations);
        if (addStation.ShowDialog() == DialogResult.OK)
        {
          departure = addStation.departure;
          waitMinutes = addStation.waitMinutes;
        }
      }
    }

    private void ConfirmButton_Click(object sender, EventArgs e)
    {
      uint routeNumber;
      float priceCoefficient;
      int coupeNumbers;
      int secondClassNumbers;
      if (!String.IsNullOrEmpty(RouteNumberTextBox.Text) && UInt32.TryParse(RouteNumberTextBox.Text, out routeNumber))
      {
        if (!String.IsNullOrEmpty(priceCoefTextBox.Text) && float.TryParse(priceCoefTextBox.Text, out priceCoefficient))
        {

          if (!String.IsNullOrEmpty(CoupeTextBox.Text) && Int32.TryParse(CoupeTextBox.Text, out coupeNumbers))
          {
            if (!String.IsNullOrEmpty(SecondClassTextBox.Text) && Int32.TryParse(SecondClassTextBox.Text, out secondClassNumbers))
            {

              int speedType = speedTypeComboBox.SelectedIndex;
              int regularity = RegularityComboBox.SelectedIndex;
              if (departure.Count > 0 && waitMinutes.Count > 0)
              {
               // if (trainManagerClient.AddRoute(sessionId, routeNumber, speedType, regularity,
               //   coupeNumbers, secondClassNumbers, departure, waitMinutes, priceCoefficient))
                if(true)
                {
                  departure.Clear();
                  waitMinutes.Clear();
                  MessageBox.Show("Маршрут успешно добавлен!");
                }
                else
                {
                  MessageBox.Show("Произошла ошибка при добавлении маршрута", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
              }
              else
              {
                MessageBox.Show("Вы не указали информацию о станциях", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
              }
            }
            else
            {
              MessageBox.Show("Неверно введено количество плацкартных вагонов", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
          }
          else
          {
            MessageBox.Show("Неверно введено количество купе-вагонов", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
          }
        }
        else
        {
          MessageBox.Show("Неверно введен коэффициент цены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      }
      else
      {
        MessageBox.Show("Неверно введен номер маршрута", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

    #endregion

  }
}
